package huixue.cn.com.rxapp.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Scroller;

import huixue.cn.com.library.util.LogUtils;
import huixue.cn.com.library.util.PixelUtils;

/**
 * Created by gongdongyang 2019/7/9
 * Describe:
 */
public class RuleView extends View {

    private int mWidth;
    private int mHeight;

    private Paint mPaint;
    private TextPaint mTextPaint;

    private int shortLineWidth;

    private int minVaule = 0;

    private int maxValue = 100;

    /**
     * 刻度字体颜色
     */
    private int textColor;
    /**
     * 刻度字体大小
     */
    private float textSize;

    private int bgColor;

    private int gradationColor;

    private int gradationGap;
    private int gradationHeight;

    private int gradation5Height;

    private int gradation10Height;

    private Scroller mScroller;

    private int mDownX;

    private int mCurrentDistance;

    /**
     * 惯性滑动最小、最大速度
     */
    private final int MIN_FLING_VELOCITY;
    private final int MAX_FLING_VELOCITY;

    /**
     * 滑动阈值
     */
    private final int TOUCH_SLOP;

    /**
     * 速度跟踪器
     */
    private VelocityTracker mVelocityTracker;


    public RuleView(Context context) {
        this(context,null);
    }

    public RuleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RuleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 初始化final常量，必须在构造中赋初值
        ViewConfiguration viewConfiguration = ViewConfiguration.get(context);

        TOUCH_SLOP = viewConfiguration.getScaledTouchSlop();
        MIN_FLING_VELOCITY = viewConfiguration.getScaledMinimumFlingVelocity();
        MAX_FLING_VELOCITY = viewConfiguration.getScaledMaximumFlingVelocity();
        init(context);
    }

    /**
     *
     * @param context
     */
    private void init(Context context) {
        textSize = PixelUtils.dp2px(12);
        shortLineWidth = PixelUtils.dp2px(1);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStrokeWidth(shortLineWidth);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);

        mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextSize(textSize);
        mTextPaint.setColor(Color.parseColor("#000000"));
        mTextPaint.setAntiAlias(true);
        mTextPaint.setDither(true);


        shortLineWidth = PixelUtils.dp2px(1);
        gradationGap = PixelUtils.dp2px(10);

        gradationHeight = PixelUtils.dp2px(20);

        gradation5Height = PixelUtils.dp2px(30);

        gradation10Height = PixelUtils.dp2px(40);

        bgColor = Color.parseColor("#f5f8f5");

        gradationColor = Color.LTGRAY;

        mScroller = new Scroller(context);



    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 1 绘制背景色
        canvas.drawColor(bgColor);

        // 2 绘制刻度、数字
        drawGradation(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth =  calculateSize(true,widthMeasureSpec);
        mHeight = calculateSize(false, heightMeasureSpec);

        setMeasuredDimension(mWidth, mHeight);
    }

    /**
     *
     * @param isWidth
     * @param spec
     * @return
     */
    private int calculateSize(boolean isWidth, int spec){
        final int mode = MeasureSpec.getMode(spec);
        final int size = MeasureSpec.getSize(spec);
        int realSize = size;
        switch (mode){
            case MeasureSpec.EXACTLY:{

            }
            break;
            case MeasureSpec.AT_MOST:
                if(!isWidth){
                    int defaultContentSize = PixelUtils.dp2px(80);
                    realSize = Math.min(realSize, defaultContentSize);
                }
                break;
            case MeasureSpec.UNSPECIFIED:

        }

        return realSize;
    }

    /**
     *
     */
    private void drawGradation(Canvas canvas){
        //
        mPaint.setColor(gradationColor);
        canvas.drawLine(0, shortLineWidth * .5f, mWidth, 0, mPaint);

        //canvas.drawColor();
        int leftExtendWidth = 10*gradationGap;
        int startNumber = minVaule+mCurrentDistance/gradationGap;
        if (startNumber < minVaule) {
            startNumber = minVaule;
        }
        LogUtils.d("startNumber","startNumber=="+startNumber);
        //刻度绘制
        for(int i=startNumber;i<maxValue*10;i++){
            int startX = i*gradationGap+leftExtendWidth-mCurrentDistance;
            int endX = startX;

            int startY = 0;
            int endY = gradationHeight;

            if(i%5==0){
                endY = gradation5Height;
            }

            if(i%10==0){
                endY = gradation10Height;
                canvas.drawText(i+"",startX,endY,mTextPaint);
            }

            canvas.drawLine(startX,startY,endX,endY,mPaint);
        }

    }

    private int mLastX;
    private boolean isMoved;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int action = event.getAction();

        final int x = (int)event.getX();
        final int y = (int) event.getY();

        if(mVelocityTracker == null){
            mVelocityTracker = VelocityTracker.obtain();
        }

        mVelocityTracker.addMovement(event);

        switch (action){
            case MotionEvent.ACTION_DOWN:
                mDownX = x;
                isMoved = false;
                break;

            case MotionEvent.ACTION_MOVE:
                final int dx = x - mLastX;
                if (!isMoved) {

                    isMoved = true;
                }

                mCurrentDistance += -dx;

                calculateValue(dx);

                break;

            case MotionEvent.ACTION_UP:
                // 计算速度：使用1000ms为单位
                mVelocityTracker.computeCurrentVelocity(1000, MAX_FLING_VELOCITY);
                // 获取速度。速度有方向性，水平方向：左滑为负，右滑为正
                int xVelocity = (int) mVelocityTracker.getXVelocity();
                if (Math.abs(xVelocity) >= MIN_FLING_VELOCITY) {
                    mScroller.fling((int)mCurrentDistance, 0, -xVelocity, 0,
                            0, maxValue*10*gradationGap, 0, 0);
                    invalidate();
                }

                break;

        }

        mLastX = x;
        return true;
    }


    /**
     * 根据distance距离，计算数值
     */
    private void calculateValue(int dx) {


        invalidate();
    }


    @Override
    public void computeScroll() {
        //super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            if (mScroller.getCurrX() != mScroller.getFinalX()) {
                mCurrentDistance = mScroller.getCurrX();
                calculateValue(mCurrentDistance);
            }
        }
    }
}
